import os
import json

class ConfigLoader:
    def __init__(self):
        self.default_config = {
            "api_keys": {
                "arxiv_api_key": "",
                "google_translate_api_key": "",
                "dingtalk_webhook_url": ""
            },
            "scheduler_settings": {
                "fetch_interval_hours": 24
            },
            "translation_settings": {
                "target_language": "zh"
            }
        }

    def load_config(self):
        env_config = self._load_from_env()
        file_config = self.load_from_file()
        return self._merge_configs(file_config, env_config)

    def _load_from_env(self):
        env_config = {
            "api_keys": {
                "arxiv_api_key": os.getenv("ARXIV_API_KEY", self.default_config['api_keys']['arxiv_api_key']),
                "google_translate_api_key": os.getenv("GOOGLE_TRANSLATE_API_KEY", self.default_config['api_keys']['google_translate_api_key']),
                "dingtalk_webhook_url": os.getenv("DINGTALK_WEBHOOK_URL", self.default_config['api_keys']['dingtalk_webhook_url'])
            },
            "scheduler_settings": {
                "fetch_interval_hours": self._safe_cast(os.getenv("FETCH_INTERVAL_HOURS", self.default_config['scheduler_settings']['fetch_interval_hours']), int, self.default_config['scheduler_settings']['fetch_interval_hours'])
            },
            "translation_settings": {
                "target_language": os.getenv("TARGET_LANGUAGE", self.default_config['translation_settings']['target_language'])
            }
        }
        return env_config

    def load_from_file(self, file_path='config.json'):
        try:
            with open(file_path, 'r') as config_file:
                file_config = json.load(config_file)
        except FileNotFoundError:
            file_config = {}
        return file_config

    def _merge_configs(self, file_config, env_config):
        merged_config = self.default_config.copy()

        for key, value in file_config.items():
            if key in merged_config and isinstance(value, dict):
                merged_config[key].update(value)
            else:
                merged_config[key] = value

        for key, value in env_config.items():
            if key in merged_config and isinstance(value, dict):
                merged_config[key].update(value)
            else:
                merged_config[key] = value

        return merged_config

    @staticmethod
    def _safe_cast(val, to_type, default=None):
        try:
            return to_type(val)
        except (ValueError, TypeError):
            return default
